package cn.stylefeng.guns.modular.gridsystem.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import cn.stylefeng.guns.core.exception.ServiceException;
import cn.stylefeng.guns.modular.gridsystem.entity.BizGateway;
import cn.stylefeng.guns.modular.gridsystem.entity.GatewayFlow;
import cn.stylefeng.guns.modular.gridsystem.enums.GatewayFlowExceptionEnum;
import cn.stylefeng.guns.modular.gridsystem.mapper.BizGatewayMapper;
import cn.stylefeng.guns.modular.gridsystem.mapper.GatewayFlowMapper;
import cn.stylefeng.guns.modular.gridsystem.model.param.GatewayFlowParam;
import cn.stylefeng.guns.modular.gridsystem.service.GatewayFLowService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Service
@Slf4j
@RequiredArgsConstructor
public class GatewayServiceImpl extends ServiceImpl<GatewayFlowMapper, GatewayFlow> implements GatewayFLowService {

    private final BizGatewayMapper gatewayMapper;

    @Override
    public void add(GatewayFlowParam param) {

        BizGateway gateway = gatewayMapper.selectOne(new LambdaQueryWrapper<BizGateway>()
                .eq(BizGateway::getGatewayCode, param.getGatewayCode()).last("limit 1"));

        if (ObjectUtil.isEmpty(gateway)) {
            log.warn(">>>  网关不存在，网关编码为：{}", param.getGatewayCode());
            throw new ServiceException(GatewayFlowExceptionEnum.GATEWAY_NOT_EXISTED);
        }

        // 设置网关主键
        param.setGatewayId(gateway.getId());
        // 设置上报时间
        param.setReportTime(DateTime.now());
        // 保存数据
        save(BeanUtil.toBean(param, GatewayFlow.class));

    }

}
